import Vue from 'vue'
import App from './app'
import axios from 'axios'
import VueRouter from 'vue-router'
import Toast from 'toon-ui/lib/components/toast'
import Routers from './routers'
import Loading from 'toon-ui/lib/components/loading'
import util from '../../assets/js/util'
import appConfig from '../../assets/js/app.config'
import '../../assets/css/common.css'

const HOST = configM.comUrl;
const TOON_CODE = util.getQueryStringHr('code') || configM.code || "" ;


// 全局配置
Vue.config.debug = false
Vue.config.devtools = false
Vue.config.silent = true
Vue.prototype.$util = util
var axiosInstance = axios.create()
Vue.prototype.$http = axiosInstance

//========创建vue实例==========
let  initVue = ()=>{
  // 并且配置路由规则
  Vue.use(VueRouter)
  const router = new VueRouter({
    mode: 'hash',
    routes: Routers
  })
  router.beforeEach((to, from, next) => {
    if( !navigator.onLine ){
      Toast({
        message: '无网络链接',
        duration: 1000, // 持续时间，默认3000毫秒
      });
      return ;
    }
    next() ;
  })
  new Vue({
    router,
    render: h => h(App)
  }).$mount('#app')

}


axiosInstance.defaults.baseURL = HOST;
axiosInstance.defaults.timeout = 10000;
axiosInstance.defaults.headers.post['content-type'] = 'application/json;charset=utf-8';
// Add a request interceptor请求拦截
axiosInstance.interceptors.request.use(function (config) {
    // 点赞接口无加载更多提示
  if(config.url.indexOf('/praise') == -1) {
      Loading.open('');
  }
  //若请求接口为获取sessionId或者从通知进来的话
  if(config.url.indexOf('/session/') == -1) {
      config.headers.sessionId = util.sessionId();
  }
  return config;
}, function (error) {
  Loading.close('')
  return Promise.reject(error);
});
// Add a response interceptor请求响应拦截
axiosInstance.interceptors.response.use(function (response) {
  Loading.close('')
  var code = response.data && response.data.meta.code
  //code解密失败,下载新的北京通
  if(code == appConfig.respCode.CODE_INVALID){
    util.updateApp('大赞门城');
  }
  if (code == appConfig.respCode.SESSION_TIMEOUT || code == appConfig.respCode.TOON_CODE_TIMEOUT || code == appConfig.respCode.TOKEN_TIMEOUT) {
    util.sessionId("");
    Toast({
      message: '操作超时',
      duration: 3000, // 持续时间，默认3000毫秒
    });
    setTimeout(function () {
      var params = { "functionType": 1 };
      window.location.href = "toon://mwap/window?params=" + JSON.stringify(params);
    }, 2000)
    return Promise.reject(response.data)
  } else {
    return response.data;
  }
}, function (error) {
  Loading.close('')
  if (error.response) {
    //Toast(error.response.status + ': ' + error.response.data);
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else {
    console.log('Error: ', error.message);
  }
  return Promise.reject(error);
});
//========axiosInstance==========
/**
 * 授权getSessionIdByTOON_CODE
 */
(function(){
  if(util.sessionId()){
    return  initVue();
  }else if (!TOON_CODE || TOON_CODE == 'null') {
    util.updateApp('大赞门城');
  }else {
    sessionStorage.setItem('toon_code', TOON_CODE)
  }
  let api = "/session/getSessionIdByToonCode" ,
  param =  {toonCode:TOON_CODE} ;
  axiosInstance.post(HOST+ api , param  )
    .then(function (res) {
      if(res.meta.code == "0" && res.data && res.data.sessionId){
        util.sessionId(res.data.sessionId);
        initVue();
      }
    })
    .catch(function (err) {
      console.log(err);

    });
})();

